package com.work.ygj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.work.ygj.common.exception.BusinessException;
import com.work.ygj.common.model.Response;
import com.work.ygj.entity.User;
import com.work.ygj.mapper.UserMapper;
import com.work.ygj.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bohang
 * @since 2022-03-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Response<User> login(User req) {
        if(StringUtils.isEmpty(req.getPassword())){
            throw new BusinessException("500001","密码不能未空");
        }
        User user = userMapper.selectUser(req.getUsername());
        if(!req.getPassword().equals(user.getPassword())){
            throw new BusinessException("500002","密码不正确");
        }
        return Response.success(user);
    }


    @Override
    public Response register(User req) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", req.getUsername()).eq("deleted", 0);
        User user = userMapper.selectOne(queryWrapper);
        if (user !=null) {
            if(Objects.equals(user.getState(),1)){
                throw new BusinessException("500001","该用户名已冻结，请联系管理员！");
            }
            throw new BusinessException("500002","该用户名已存在！");
        }
        userMapper.insert(req);
        return Response.success();
    }

    @Override
    public Response updateUserInfo(User user) {
        userMapper.updateById(user);
        return Response.success();
    }
}
